package tr.edu.metu.is.mega.server.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import tr.edu.metu.is.mega.client.service.GwtAuthenticationService;
import tr.edu.metu.is.mega.common.dto.UserDTO;
import tr.edu.metu.is.mega.server.business.UserManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Implementation of GWT authentication service.
 */
public class GwtAuthenticationServiceImpl extends RemoteServiceServlet implements GwtAuthenticationService {

    private static final long serialVersionUID = -7336842951749837206L;

    public static final String USER_SESSION_STRING = "mega_user";

    private final UserManager userManager;

    /**
     * Default constructor.
     */
    public GwtAuthenticationServiceImpl() {
        userManager = new UserManager();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UserDTO login(String userName, String password) {
        HttpServletRequest request = getThreadLocalRequest();
        HttpSession session = request.getSession(true);
        UserDTO user = userManager.login(userName, password);
        if (user != null) {
            session.setAttribute(USER_SESSION_STRING, user);
        }
        return user;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void logout() {
        HttpServletRequest request = getThreadLocalRequest();
        HttpSession session = request.getSession(true);
        session.setAttribute(USER_SESSION_STRING, null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UserDTO getFromSession() {
        HttpServletRequest request = getThreadLocalRequest();
        HttpSession session = request.getSession(true);
        return (UserDTO) session.getAttribute(USER_SESSION_STRING);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UserDTO getCurrentUser() {
        HttpServletRequest request = getThreadLocalRequest();
        HttpSession session = request.getSession(true);
        UserDTO user = (UserDTO) session.getAttribute(USER_SESSION_STRING);
        return user;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateCurrentUser(UserDTO user) {
        HttpServletRequest request = getThreadLocalRequest();
        HttpSession session = request.getSession(true);
        session.setAttribute(USER_SESSION_STRING, user);
    }

}
